package com.aeye.mbr.upms.rpc.service.impl;


import com.aeye.mbr.common.plugin.mapper.BaseServiceImpl;
import com.aeye.mbr.common.result.BootstrapTableParams;
import com.aeye.mbr.common.result.BootstrapTableResult;
import com.aeye.mbr.upms.dao.model.UpmsArea;
import com.aeye.mbr.upms.dao.model.UpmsOrganization;

import com.aeye.mbr.upms.rpc.api.UpmsAreaService;

import com.aeye.mbr.upms.rpc.mapper.UpmsAreaMapper;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import tk.mybatis.mapper.entity.Example;

import java.util.Collections;
import java.util.List;

/**
 * UpmsOrganizationService实现
 * Created by shuaeye.mbr on 2017/3/20.
 */
@Service
@Transactional
public class UpmsAreaServiceImpl extends BaseServiceImpl<UpmsArea> implements UpmsAreaService {

    private static Logger _log = LoggerFactory.getLogger(UpmsAreaServiceImpl.class);

    @Autowired
    UpmsAreaMapper upmsAreaMapper;

    @Override
    public BootstrapTableResult<UpmsArea> selectUpmsAreaByParams(BootstrapTableParams params, String parentCode) {
        BootstrapTableResult result = new BootstrapTableResult();
        if (params != null) {
            PageHelper.startPage(params.getPage(), params.getLimit());
            Example example = new Example(UpmsArea.class);
            Example.Criteria criteria = example.createCriteria();
            String sort = params.getSort();
            String order = params.getOrder();
            if (!StringUtils.isBlank(sort) && !StringUtils.isBlank(order)) {
                example.setOrderByClause(sort + " " + order);
            }
            String search = params.getSearch();
            if (StringUtils.isNotBlank(search)) {
                example.or()
                        .andLike("name", "%" + search + "%");
            }
            if(StringUtils.isNotEmpty(parentCode)){
                example.and().andLike("path","%"+parentCode+"%");
            }
            List<UpmsArea> permissions = upmsAreaMapper.selectByExample(example);
            if (!CollectionUtils.isEmpty(permissions)) {
                if (permissions instanceof Page) {
                    Page<UpmsOrganization> pls = (Page) permissions;
                    result.setTotal((int) pls.getTotal());
                    result.setRows(pls.getResult());
                } else {
                    result.setTotal(permissions.size());
                }
                result.setRows(permissions);
            }else{
                result.setTotal(0);
                result.setRows(Collections.emptyList());
            }
        }
        return result;
    }
}